package com.example.bookstore.service

import com.example.bookstore.dao.CartDetailDao
import com.example.bookstore.entity.BookEntity
import com.example.bookstore.entity.CartDetailEntity
import com.example.bookstore.entity.CartEntity
import com.example.bookstore.exception.SecurityException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * Created by IntelliJ IDEA.
 * User: lvshe
 * Date: 2019/8/10
 * Time: 15:10
 */
@Service
class CartDetailService : BaseService<CartDetailDao, CartDetailEntity>() {


    @Autowired
    private lateinit var cartService: CartService
    @Autowired
    private lateinit var bookService: BookService


    fun getByBookAndCartOrNull(book: BookEntity, cart: CartEntity): CartDetailEntity? {
        return dao.findByBookAndCart(book, cart)
    }

    override fun save(entity: CartDetailEntity): CartDetailEntity {
        if (checkCartDetailExists(entity)) throw SecurityException("该书籍已加入购物车，请使用 Update")
        return super.save(entity)
    }


    override fun update(entity: CartDetailEntity): CartDetailEntity {
        if (!checkCartDetailExists(entity)) throw SecurityException("该书籍未加入购物车，请使用 Save")
        return super.save(entity)
    }

    private fun checkCartDetailExists(entity: CartDetailEntity): Boolean {
        bookService.getById(entity.book.id)
        cartService.getById(entity.cart.id)
        return dao.findByBookAndCart(entity.book, entity.cart) != null
    }


}